package com.etc.my.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.etc.my.aily.AlipayConfig;
import com.etc.my.entity.Car;
import com.etc.my.entity.Order;
import com.etc.my.entity.User;
import com.etc.my.service.CarService;
import com.etc.my.service.OrderService;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author: Admin
 * @time: 2022/10/29 14:54
 */

@Controller
public class AilyPayController {

    Logger logger = LogManager.getLogger(AilyPayController.class);

    @Autowired
    OrderService orderService;

    @Autowired
    CarService carService;
    /**
     * 支付跳转
     * @param car
     * @param session
     * @return
     */
    @RequestMapping(value = "/toAlipay",produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String toAlipay(Car car, HttpSession session){
       User user = (User) session.getAttribute("loginuser");

        if(true){

            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key,
                    "json",
                    AlipayConfig.charset,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type);
            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //订单编号 日期+carid+userid
            String order_id =System.currentTimeMillis()+"="+car.getCar_id() +"="+user.getUser_id();
            //订单价格 定金价格是汽车（万元）的0.1
            String order_price = String.valueOf(car.getCar_price() * 10);
            //订单名称
            String car_name = car.getCar_name();
            //商品描述
            String body = "定金";

            // 该笔订单允许的最晚付款时间，逾期将关闭交易。
            // 取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
            String timeout_express = "15m";
            if(null!=order_price){ //支付金额不等于空
                alipayRequest.setBizContent("{\"out_trade_no\":\""+ order_id +"\","
                        + "\"total_amount\":\""+ order_price +"\","
                        + "\"subject\":\""+ car_name +"\","
                        + "\"body\":\""+ body +"\","
                        + "\"timeout_express\":\""+ timeout_express +"\","
                        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

                try{
                    String result = alipayClient.pageExecute(alipayRequest).getBody();
                    return result;
                }catch (AlipayApiException e ){
                    logger.error(e);
                }
            }
            return "订单信息错误!";
        }
        return "没有登录";
    }


    /**
     * 支付成功返回的控制器
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/alipayReturnUrl")
    @Transactional
    public String alipayReturnUrl(Model model, HttpServletRequest request, HttpServletResponse response)throws Exception{

        //获取数据
        Map<String,String[]> requestParams = request.getParameterMap();
        //创建一个空map用来存放处理完乱码的map
        Map<String,String> params = new HashMap();
        //迭代器遍历
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        if(signVerified){
            //商户订单号
            String order_code = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String order_price = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            String order_datetime = new String(request.getParameter("timestamp").getBytes("ISO-8859-1"),"UTF-8");
            //调用添加订单业务逻辑
//            System.out.println("商户订单号："+order_code+"---付款金额:"+order_price+"时间:"+order_datetime);
//            System.out.println("————————————添加订单完成支付————————————");
            Order order = new Order();

            //分割字符串获得car_id 和 user_id
            String[] split = order_code.split("=");

            order.setOrder_code(String.valueOf(System.currentTimeMillis()));
            order.setOrder_datetime(order_datetime);
            //获取汽车id
            Car car = new Car();
            car.setCar_id(split[1]);
            order.setOrder_car(car);
            //获取用户id
            User user = new User();
            user.setUser_id(Integer.valueOf(split[2]));
            //从session获取
            //User user = request.getSession().getAttribute("loginuser");
            order.setOrder_user(user);
            order.setOrder_status("支付完成");
            order.setOrder_price(new Double(order_price));
            //插入订单
            boolean insertOrderFlag = orderService.insertOrder(order);
            //修改车辆状态
            boolean updateCarStatusFlag = carService.updateCarStatus(car.getCar_id(), "下架");
            if(insertOrderFlag&&updateCarStatusFlag){
                //订单插入成功
                return "order";
            }
        }else{
            System.out.println("-------------没有支付-----------------");
        }
        return "index";
    }

}
